<?php
if (!defined('WPSR_ACCESS')) { exit; }



/**
 * WPsrFile class.
 * 
 * @extends WPsrAdm
 */
class WPsrFile extends WPsrAdm
{




	/**
	 * assign function.
	 * 
	 * @access private
	 * @param int $owner
	 * @param mixed $type
	 * @param string $tmppath
	 * @param string $path
	 * @param int $album
	 * @param int $level
	 * @return void
	 */
	function assign($owner, $type, $tmppath, $path, $album, $level) {
		global $wpdb;

		$i = 0;

		if ($_POST['filename'] > 0 || $_POST['file'] > 0) {
			if ($_POST['palb'] && $_POST['palb'] > 1) {
				if ($_POST['file'] > 0) {
					foreach ($_POST['file'] as $extfile) {
						/**
						 * Picture already in Insert queue - change assigned album in DB
						 */
						$wpdb->update(WPSR_DB_I, compact('album', 'level'), array('id' => $extfile));
						$i++;
					}
				}
				if ($_POST['filename'] > 0) {
					foreach ($_POST['filename'] as $newfile) {
						/**
						 * New Picture - move to "waiting" and create new Insert queue DB entry
						 */
						$filename = $this->IfExistsRename($newfile, $path);
						if (rename($tmppath.$newfile, $path.$filename)) {
							$file = $filename;
							$imagesize = getimagesize($path.$filename);
							$size = filesize($path.$filename);
							$fsize = $this->byteConvert($size);
							$xsize = $imagesize[0];
							$ysize = $imagesize[1];
							$date = date('Y-m-d H:i:s');
							$id = NULL;
							$wpdb->insert(WPSR_DB_I, compact('id', 'date', 'type', 'owner', 'file', 'album', 'level', 'xsize', 'ysize', 'fsize'));
							$i++;
						}
						else {
							$this->message[] = '5';
						}
					}
				}
				$this->message[] = '6';
			}
			else {
				$this->message[] = '7';
			}
		}
	}





	/**
	 * unassign function.
	 * 
	 * @access public
	 * @param string $tmppath
	 * @param string $path
	 * @param mixed $type
	 * @return void
	 */
	function unassign($tmppath, $path, $type) {
		global $wpdb;

		$i = 0;

		if ($_POST['file'] > 0) {
			foreach ($_POST['file'] as $extfile) {
				/**
				 * Picture already in Insert queue - change DB entry
				 */
				$q = $wpdb->prepare("SELECT file FROM ".WPSR_DB_I." WHERE id = $extfile LIMIT 1");
				$dbfile = $wpdb->get_row($q);

				$filename = $this->IfExistsRename($dbfile->file, $tmppath);
				if (rename($path.$dbfile->file, $tmppath.$filename)) {
					/**
					 * Keep in history instead of deleting from DB
					 * $wpdb->query("DELETE FROM ".WPSR_DB_I." WHERE id = ".$extfile);
					 */
					$done_date = date('Y-m-d H:i:s');
					$wpdb->update(WPSR_DB_I, compact('done_date', 'type'), array('id' => $extfile));
					$i++;
				}
				else {
					$this->message[] = '5';
				}
			}
			$this->message[] = '8';
		}
	}





	/**
	 * deleteuploads function.
	 * 
	 * @access public
	 * @param string $tmppath
	 * @param string $path
	 * @param mixed $type
	 * @return void
	 */
	function deleteuploads($tmppath, $path, $type) {
		global $wpdb;

		$i = 0;

		if ($_POST['filename'] > 0 || $_POST['file'] > 0) {
			foreach ($_POST['file'] as $extfile) {
				/**
				 * Picture already in Insert queue - delete from HD and change entry in DB
				 */
				$q = $wpdb->prepare("SELECT file FROM ".WPSR_DB_I." WHERE id = $extfile LIMIT 1");
				$dbfile = $wpdb->get_row($q);

				if (unlink($path.$dbfile->file)) {
					/**
					 * Keep in history instead of deleting from DB
					 * $wpdb->query("DELETE FROM ".WPSR_DB_I." WHERE id = ".$extfile);
					 */
					$done_date = date('Y-m-d H:i:s');
					$wpdb->update(WPSR_DB_I, compact('done_date', 'type'), array('id' => $extfile));
					$i++;
				}
				else {
					$wpsr->message[] = '9';
				}
			}
			foreach ($_POST['filename'] as $newfile) {
				/**
				 * New Picture - delete from HD
				 */
				if (!unlink($tmppath.$newfile)) {
					$wpsr->message[] = '9';
				}
			}
		}
	}





	/**
	 * deleteFile function.
	 * 
	 * @access public
	 * @param string $path
	 * @param string $file
	 * @return bool
	 */
	function deleteFile($path, $file) {
		$psizes = explode(",", WPSR_PSIZES);
		for ($i = 0; $i < count($psizes); $i++) {
			if ($psizes[$i] != 'full') {
				if (is_file(WPSR_FILEPATH.$psizes[$i].'/'.$path.$file)) {
					unlink(WPSR_FILEPATH.$psizes[$i].'/'.$path.$file);
					/**
					 * Try to remove directory if empty; supress error
					 */
					@rmdir(substr(WPSR_FILEPATH.$psizes[$i].'/'.$path, 0, -1));
				}
				else {
					return false;
				}
			}
			else {
				if (is_file(WPSR_ORG_FILEPATH.$path.$file)) {
					unlink(WPSR_ORG_FILEPATH.$path.$file);
					/**
					 * Try to remove directory if empty; supress error
					 */
					@rmdir(substr(WPSR_ORG_FILEPATH.$path, 0, -1));
				}
				else {
					return false;
				}
			}
		}
		return true;
	}





	/**
	 * checkDir function.
	 * 
	 * @access public
	 * @return void
	 */
	function checkDir() {
		global $user_ID;

		$this->checkUploadDir($user_ID);
		$this->checkWaitingDir($user_ID);
	}





	/**
	 * checkPicDirs function.
	 * 
	 * @access public
	 * @param string $path
	 * @return bool
	 */
	function checkPicDirs($path) {
		$psizes = explode(",", WPSR_PSIZES);
		for ($i = 0; $i < count($psizes); $i++) {
			if ($psizes[$i] != 'full') {
				if (WPsrFile::checkPicDir(WPSR_FILEPATH.$psizes[$i]) == false) {
					return false;
				}
				elseif (WPsrFile::checkPicDir(WPSR_FILEPATH.$psizes[$i].'/'.$path) == false) {
					return false;
				}
			}
			else {
				if (WPsrFile::checkPicDir(WPSR_ORG_FILEPATH) == false) {
					return false;
				}
				elseif (WPsrFile::checkPicDir(WPSR_ORG_FILEPATH.$path) == false) {
					return false;
				}
			}
		}
		return true;
	}





	/**
	 * checkPicDir function.
	 * 
	 * @access public
	 * @param string $path
	 * @return bool
	 */
	function checkPicDir($path) {
		$ok = true;
		if (!file_exists($path)) {
			if (mkdir($path)) {
				chmod($path, 0775);
			}
			else {
				$ok = false;
			}
		}
		return $ok;
	}





	/**
	 * checkUploadDir function.
	 * 
	 * @access public
	 * @param int $user_ID
	 * @return bool
	 */
	function checkUploadDir($user_ID) {
		global $user_ID;

		$path = WPSR_FILEPATH."upload/".$user_ID;

		if (file_exists($path)) {
			return true;
		}
		else {
			if (mkdir($path)) {
				chmod($path, 0775);
				return true;
			}
			else {
				$this->message[] = '10';
				return false;
			}
		}
	}





	/**
	 * checkWaitingDir function.
	 * 
	 * @access public
	 * @param int $user_ID
	 * @return bool
	 */
	function checkWaitingDir($user_ID) {
		global $user_ID;

		$path = WPSR_FILEPATH."waiting/".$user_ID;

		if (file_exists($path)) {
			return true;
		}
		else {
			if (mkdir($path)) {
				chmod($path, 0775);
				return true;
			}
			else {
				$this->message[] = '11';
				return false;
			}
		}
	}
	
	




	/**
	 * IfExistsRename function.
	 * 
	 * @access public
	 * @param mixed $file_name
	 * @param mixed $new_location
	 * @return mixed
	 */
	function IfExistsRename($file_name, $new_location) {
		if (substr($new_location, -1, 1) != "/") {
			$new_location += $new_location . "/";
		}

		if (file_exists($new_location . $file_name)) {
			$cont = 0;
			$original_fila_name = $file_name;
			do {
				$file_parts = explode(".", $original_fila_name, 2);
				$file_name = $file_parts[0] . "_" . $cont . "." . $file_parts[1];
				$cont++;
			}while (file_exists($new_location . $file_name));
		}

		return $file_name;
	}





	/**
	 * getFiles function.
	 * 
	 * @access public
	 * @param int $uid
	 * @return array
	 */
	function getFiles($uid) {

		$path = WPSR_FILEPATH."upload/".$uid;
		$files = array();
		$files1 = scandir($path);
		foreach ($files1 as $file) {
			if ($this->okfiletype($file)) {
				$imagesize = getimagesize($path.'/'.$file);
				$size = filesize($path.'/'.$file);
				$size = $this->byteConvert($size);
				$files[] = array('fn' => $file, 'xsize' => $imagesize[0], 'ysize' => $imagesize[1], 'fsize' => $size);
			}
		}
		return $files;
	}





	/**
	 * getWaitingFiles function.
	 * 
	 * @access public
	 * @param int $uid
	 * @return object
	 */
	function getWaitingFiles($uid) {

		global $wpdb;
		$q = $wpdb->prepare("SELECT id, file, album, level, xsize, ysize, fsize FROM ".WPSR_DB_I." WHERE done_date IS NULL AND owner = '$uid' AND type = 1 ORDER BY id");
		return $wpdb->get_results($q);
	}




	/**
	 * getRegenerateFiles function.
	 * 
	 * @access public
	 * @param int $uid
	 * @return object
	 */
	function getRegenerateFiles($uid) {

		global $wpdb;
		$q = $wpdb->prepare("SELECT id, file, path FROM ".WPSR_DB_I." WHERE done_date IS NULL AND owner = '$uid' AND type = 2 ORDER BY id");
		return $wpdb->get_results($q);
	}




	/**
	 * getWaitingFile function.
	 * 
	 * @access public
	 * @param int $uid
	 * @return object
	 */
	function getWaitingFile($uid, $type = 1) {

		global $wpdb;
		$q = $wpdb->prepare("SELECT id, file, album, level, xsize, ysize, fsize, path FROM ".WPSR_DB_I." WHERE done_date IS NULL AND owner = '$uid' AND type = $type ORDER BY id LIMIT 1");
		return $wpdb->get_row($q);
	}





	/**
	 * okfiletype function.
	 * 
	 * @access public
	 * @param string $filename
	 * @return void
	 */
	function okfiletype($filename) {
		$allowed = explode(",", WPSR_FILETYPE);
		for ($i = 0; $i < count($allowed); $i++) {
			if (strtolower($allowed[$i]) == strtolower(substr($filename, -3))  || strtolower($allowed[$i]) == strtolower(substr($filename, -4)))
				return true;
		}
		return false;
	}





	/**
	 * byteConvert function.
	 * 
	 * @access public
	 * @param int $bytes
	 * @return string
	 */
	function byteConvert($bytes) {

		$sizemb = ($bytes / 1024)/1024;
		$sizemb = round($sizemb, 2);
		return $sizemb." MB";
	}


}


?>